*cd V:\PIER_Data\Yating\Data

***Merge all the product data one by one and save seperately to the final consumption data (list00)
dis "$S_DATE, $S_TIME"	

cd /u/flashscratch/y/yatingch
*cd /u/home/y/yatingch
set more off
cap log close


use ./account_usetype_parcel_block_cons_2010_2014_matchList3_ee1015_Final, clear

gen day=.
replace day=31 if month==1 | month==3 | month==5 | month==7 | month==8 | month==10 | month==12
replace day=28 if month==2
replace day=30 if month==4 | month==6 |month==9 |month==11 
gen time=mdy(month, day, year)
format time %td


dis "$S_DATE, $S_TIME"		


***merge all the product 
forvalues i=1/11{
	sort accounts_id year month
	cap drop _merge
	merge accounts_id using /u/home/y/yatingch/by_program_product/prod`i'_1015, keep("install_date_prod`i' ")
	***check the merging
	tab _merge
	drop if _merge==2
	drop _merge
	
	gen running_prod`i'=time-install_date_prod`i'
	*gen running_prod`i'_claim=time-claimtime_prod`i'
	dis "treatment in program `i'"
	gen treat_prod`i'=1 if time>=install_date_prod`i'
	replace treat_prod`i'=0 if treat_prod`i'==.
	tab treat_prod`i'
}
		

******* Generate household-by-calendar month identifier ----------------------------------------------*;
dis "$S_DATE, $S_TIME"		
sort counties year
sort accounts year month
gen log_usage=log(usage)

*------- Set tolerance for the double-demeaning algorithm --------------------*;
cap ssc install reg2hdfe
local tol tol(0.0001)
*greenstone, household-month, month by year
egen HxM = group(accounts_id month)
egen T = group(year month)
dis "$S_DATE, $S_TIME"		

*dropping outliers
sum usage, detail
gen touse= inrange(usage, `r(p1)', `r(p99)')
tab touse
drop if touse==0
sum usage

reg2hdfe usage treat_prod1 treat_prod2 treat_prod3 treat_prod4 treat_prod5 treat_prod6 treat_prod7 treat_prod8 treat_prod9 treat_prod10 treat_prod11, id1(HxM) id2(T) cluster(megaparcels_id) `tol'
dis "$S_DATE, $S_TIME"	

